package com.freemypay.test.并发.共享受限资源.不正确的访问资源;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock.tryLock();
 * 仅在调用时锁为空闲状态才获取该锁
 * 若没有获取到锁，可以继续去做其他事情，相对synchronized颗粒更细。
 * @author yesixian
 * @date 2018年5月15日
 */
public class AttemptLocking {
	private ReentrantLock lock = new ReentrantLock();
	
	public void untimed() {
		boolean captured = lock.tryLock();
		try {
			System.out.println("tryLock(): " + captured);
		} finally {
			if(captured) {
				lock.unlock();
			}
		}
	}

	public void timed() {
		boolean captured = false;
		try {
			captured = lock.tryLock(2, TimeUnit.SECONDS);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		try {
			System.out.println("tryLock(2, TimeUnit.SECONDS): " + captured);
		} finally {
			if(captured) {
				lock.unlock();
			}
		}
	}
	
	public static void main(String[] args) {
		final AttemptLocking al = new AttemptLocking();
		al.untimed();
		al.timed();
		new Thread() {
			{setDaemon(true);}
			
			@Override
			public void run() {
				al.lock.lock();
				System.out.println("acquired");
			};
		}.start();
		Thread.yield();
		al.untimed();
		al.timed();
	}
}
